package com.hmall.gateway.filter;

import cn.hutool.core.util.StrUtil;
import com.hmall.common.utils.CollUtils;
import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Slf4j
@Component
@EnableConfigurationProperties(AuthProperties.class) //将配置类加载到ioc容器中
@RequiredArgsConstructor
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private final AuthProperties authProperties;

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    private final JwtTool jwtTool;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.判断请求路径是否在白名单中，如果在放行
        //当前请求的路径
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String uri = request.getPath().toString();
        log.info("当前请求的路径：{}", uri);
        //获取白名单
        List<String> excludePaths = authProperties.getExcludePaths();
        //判断当前请求的路径uri是否在白名单中
        for (String excludePath : excludePaths) {
            if (antPathMatcher.match(excludePath, uri)) {
                //当前请求在白名单中，放行
                log.info("当前请求在白名单中，放行，{}", uri);
                return chain.filter(exchange);
            }
        }

        //2.从请求头中获取token
        String token = request.getHeaders().getFirst("authorization");
        if (StrUtil.isEmpty(token)) {
            //token为空，返回401
            response.setRawStatusCode(401);
            return response.setComplete();
        }

        //3. 校验token
        Long userId;
        try {
            userId = jwtTool.parseToken(token);
        } catch (Exception e) {
            //校验不通过 返回401
            response.setRawStatusCode(401);
            return response.setComplete();
        }
        // 4. 将用户id传递给微服务
        request.mutate().header("user-info", userId.toString());

        //5.放行
        log.info("token校验通过，放行uri:{}, userId:{}", uri, userId);
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
